import os
os.chdir("E:\\code_exercises\\python_exer\\temp")
os.getcwd()

def find_class_name(filepath):
    classname = ''
    with open(filepath, 'r', encoding=('utf-8')) as f1:
        for line in f1:
            if "class " in line and ":" in line:
                classname = line.split('(')[0][6:]
                break
    
    # print(classname)
    return classname

def append_params(code_list):
    code_list.append("    param.soc = ''")
    code_list.append("    param.tcon = ''")
    code_list.append("    param.serial = ''")
    code_list.append("    param.pg = ")
    code_list.append("    param.timeout = 1")
    return code_list

def append_process(code_list):
    code_list.append("    auto_test.prepare()")
    code_list.append("    auto_test.process()")
    code_list.append("    auto_test.clean()")
    return code_list

if __name__ == '__main__':
    
    rootdir = "E:\\code_exercises\\python_exer\\temp\\"
    savefile = rootdir + "001_test.py"
    code_list = []
    classname_list = []
    paramstr = "(param.soc, param.tcon, param.serial, param.pg, param.timeout)"
    
    filenames = os.listdir(rootdir)
    
    code_list.append('# coding: utf-8')
    
    for filename in filenames:
        if filename == '__pycache__' or filename == '__init__.py':
            continue

        filepath = rootdir + filename
        classname = find_class_name(filepath)
        
        if classname != '':
            import_line = "from " + filename.split('.')[0] + " " + "import" + " " + classname
            code_list.append(import_line)
            classname_list.append(classname)

    code_list.append('\n')
    
    code_list.append("if __name__ == '__main__':")
    code_list.append('\n')
    code_list = append_params(code_list)
    code_list.append('\n')
    for classname in classname_list:
        code_create_case = "    " + "auto_test = " + classname + paramstr
        code_list.append(code_create_case)
        code_list = append_process(code_list)
        code_list.append('\n')
    
    for i in code_list:
        print(i)

